<script setup lang="ts">
defineOptions({
  name: "ALL_FAB_MONITORING_SPECOVERVIEW"
});

import { ref, onMounted, onUnmounted, markRaw, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { PxMessage } from "px-ui";
import { Edit, Delete, Histogram } from "@px-ui/icons-vue";
import commonTable from "@/views/common/components/commonTable/index.vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import batchImport from "./components/batchImport.vue";
import { queryFabSPECList, removeFabSPEC, importFabSPECData } from "@/api/modules/fab";
import { useRouterStoreHook } from "@/store/modules/router";
import { useSearchOption, useTableCloumns, initDefaultColor } from "./hooks";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { useMessageBox } from "@/hooks/useCommon";
import previewSpec from "./components/previewSpec.vue";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import { PxMessageBox } from "px-ui";

const { proxy }: any = getCurrentInstance();

const router = useRouter();
const routerStore = useRouterStoreHook();

const searchLoading = ref<boolean>(false);
const gap = 80;
const defaultHeight = 606;
const fabListTableRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);
const scrollbarHeight = ref<number>(defaultHeight);
const searchOption = ref<Array<CommonSearch.SearchOption>>(useSearchOption());
const tableCloumns = ref<Array<CommonTable.TableCloumnsType>>(useTableCloumns());
const importBottleVisible = ref<boolean>(false);
const previewSpecVisible = ref<boolean>(false);
const previewSpecData = ref<Record<string, any>>(null);
const eqpId = ref<string>("");
const ids = ref<Array<any>>([]);

const operationOptions: Array<CommonTable.operationOptionItemType> = [
  {
    content: "编辑",
    auth: `${routerStore.subject}_FAB_MONITORING_SPECOVERVIEW_EDIT_BTN`,
    icon: markRaw(Edit),
    click: (scope: any) => edit(scope.row)
  },

  {
    content: "预览",
    auth: `${routerStore.subject}_FAB_MONITORING_SPECOVERVIEW_PREVIEW_BTN`,
    icon: markRaw(Histogram),
    click: (scope: any) => preview(scope.row)
  },

  {
    content: "删除",
    auth: `${routerStore.subject}_FAB_MONITORING_SPECOVERVIEW_DELETE_BTN`,
    type: "danger",
    icon: markRaw(Delete),
    click: (scope: any) => del(scope.row)
  }
];

const params = ref<any>({});

let defaultParams: any = {};
let currentParams: any = {};

const headerCellStyleFn = ({ row, column, rowIndex, columnIndex }) => {
  let style = {};
  switch (columnIndex) {
    case 3:
      style["text-align"] = "center";
      break;
    case 8:
      style["background-color"] = initDefaultColor("uslColor");
      style["color"] = "#fff";
      break;
    case 9:
      style["background-color"] = initDefaultColor("uclColor");
      style["color"] = "#fff";
      break;
    case 10:
      style["background-color"] = initDefaultColor("uwlColor");
      style["color"] = "#fff";
      break;
    case 11:
      style["background-color"] = initDefaultColor("targetColor");
      style["color"] = "#fff";
      break;
    case 12:
      style["background-color"] = initDefaultColor("lwlColor");
      style["color"] = "#fff";
      break;
    case 13:
      style["background-color"] = initDefaultColor("lclColor");
      style["color"] = "#fff";
      break;
    case 14:
      style["background-color"] = initDefaultColor("lslColor");
      style["color"] = "#fff";
      break;
    default:
      break;
  }
  return style;
};

const submitHandler = (flag: boolean = false) => {
  const message = "导入成功！";
  PxMessage.success(message);
  commonTableRef.value.queryTableData();
};

const updateParams = () => {
  params.value = { ...defaultParams, ...currentParams };
};

const submitSearchFormHandler = (form: any) => {
  currentParams = { ...currentParams, ...form };
  updateParams();
};

const edit = (row: any) => {
  const { id = "" } = row;
  const className = routerStore.getSubject.toLowerCase();
  const path = `/${className}/fab/monitoring/specOverView/setSpec`;
  const query = { id };
  router.push({ path, query });
};

const preview = (row: any) => {
  const { eqpId: eqpId_ = "" } = row;
  eqpId.value = eqpId_;
  previewSpecData.value = row;
  previewSpecVisible.value = true;
};

const del = (row: any) => {
  const { id = "", jobId = "" } = row;
  const msg = `确定删除 ${jobId} 吗？`;
  useMessageBox("delete", msg, async () => {
    await removeFabSPEC(id);
    await commonTableRef.value.queryTableData();
    PxMessage.success("删除成功！");
  });
};

const addHandler = () => {
  const className = routerStore.getSubject.toLowerCase();
  const path = `/${className}/fab/monitoring/specOverView/setSpec`;
  router.push({ path });
};

const selectionChangeHandler = (val: Array<any>) => {
  ids.value = [];
  if (val?.length) {
    ids.value = val.map(item => item.id);
  }
};

const downloadHandler = useThrottleFn(() => {
  const url = "/fab/api/v1/spcIndicator/downloadTemplate";
  proxy.download("post", url);
  PxMessageBox.alert("正在下载模板，数据处理可能需要一定时间，请耐心等待，数据准备完毕将直接下载。", "下载模板", {
    confirmButtonText: "我知道了"
  });
}, delay);

const batchImportHandler = useThrottleFn(() => {
  importBottleVisible.value = true;
}, delay);

const batchExportHandler = useThrottleFn(() => {
  if (!!ids.value.length) {
    const url = "/fab/api/v1/spcIndicator/list/export";
    const params = commonTableRef.value.getParams();
    proxy.download("post", url, { ...params, ids: ids.value });
    PxMessageBox.alert("正在导出您筛选的数据，数据处理可能需要一定时间，请耐心等待，数据准备完毕将直接下载。", "批量导出", {
      confirmButtonText: "我知道了"
    });
  } else {
    PxMessage.error("请选择指标！");
  }
}, delay);

onMounted(async () => {
  await useUpdateDomHeight(scrollbarHeight, fabListTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div v-loading="searchLoading" class="specOverView-content">
    <div class="specOverView-content-search">
      <commonSearch
        v-if="searchOption?.length"
        ref="commonSearchRef"
        v-model:loading="searchLoading"
        :row-num="4"
        :option="searchOption"
        @submit="submitSearchFormHandler"
        @reset="submitSearchFormHandler"
      />
    </div>
    <div class="specOverView-content-btns">
      <px-button v-has="`${routerStore.getSubject}_FAB_MONITORING_SPECOVERVIEW_ADD_BTN`" type="primary" @click="addHandler">新增</px-button>
      <!-- 下载和导入暂时不做  2024-08-09   -->
      <px-button v-has="`${routerStore.getSubject}_FAB_MONITORING_SPECOVERVIEW_UPLOAD_BTN`" plain type="primary" @click="downloadHandler">
        下载模板
      </px-button>
      <px-button v-has="`${routerStore.getSubject}_FAB_MONITORING_SPECOVERVIEW_IMPORT_BTN`" plain type="primary" @click="batchImportHandler">
        批量导入
      </px-button>
      <px-button v-has="`${routerStore.getSubject}_FAB_MONITORING_SPECOVERVIEW_EXPORT_BTN`" plain type="primary" @click="batchExportHandler">
        批量导出
      </px-button>
    </div>
    <div ref="fabListTableRef" class="specOverView-content-table">
      <commonTable
        ref="commonTableRef"
        indexNeed
        selection
        :operationOptions="operationOptions"
        :tableCloumns="tableCloumns"
        :height="scrollbarHeight"
        :axiosApi="queryFabSPECList"
        :params="params"
        :header-cell-style="headerCellStyleFn"
        @selection-change="selectionChangeHandler"
      />
    </div>
    <batchImport v-if="importBottleVisible" v-model="importBottleVisible" :uploadApi="importFabSPECData" @submit="submitHandler" />
    <previewSpec v-if="previewSpecVisible" v-model="previewSpecVisible" :data="previewSpecData" :eqpId="eqpId" />
  </div>
</template>

<style lang="scss" scoped>
.specOverView-content {
  box-sizing: border-box;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;

  .specOverView-content-btns {
    margin-top: 16px;
  }

  .specOverView-content-table {
    margin-top: 16px;
  }
}
</style>
